<template>
  <div class="profile-container">
    <!-- 个人信息卡片 -->
    <el-card class="profile-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-avatar :size="50" src="/avatar.png" class="user-avatar" />
            <div class="user-info">
              <h2 class="user-name">{{ student?.name || '加载中...' }}</h2>
              <p class="user-role">{{ student?.college || '院系信息' }}</p>
            </div>
          </div>
          <div class="header-right">
            <el-button 
              type="primary" 
              @click="toggleEdit"
              :icon="isEditing ? 'Close' : 'Edit'"
              :loading="loading"
            >
              {{ isEditing ? '取消编辑' : '编辑信息' }}
            </el-button>
          </div>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="4" animated />
      </div>

      <div v-else-if="error" class="error-container">
        <el-result
          icon="error"
          :title="error"
          sub-title="请检查网络连接或联系管理员"
        >
          <template #extra>
            <el-button type="primary" @click="loadProfile">重新加载</el-button>
          </template>
        </el-result>
      </div>

      <div v-else-if="student" class="profile-content">
        <el-row :gutter="24">
          <!-- 左侧：基本信息 -->
          <el-col :span="12">
            <div class="info-section">
              <div class="section-title">
                <el-icon><User /></el-icon>
                <span>基本信息</span>
              </div>
              <div class="info-grid">
                <div class="info-item">
                  <label class="info-label">姓名</label>
                  <div v-if="!isEditing" class="info-value">{{ student.name }}</div>
                  <el-input v-else v-model="formData.name" placeholder="请输入姓名" />
                </div>
                <div class="info-item">
                  <label class="info-label">院系</label>
                  <div v-if="!isEditing" class="info-value">{{ student.college }}</div>
                  <el-input v-else v-model="formData.college" placeholder="请输入院系" />
                </div>
              </div>
            </div>

            <div class="info-section">
              <div class="section-title">
                <el-icon><Phone /></el-icon>
                <span>联系方式</span>
              </div>
              <el-form 
                :model="formData" 
                :rules="rules" 
                ref="contactFormRef" 
                label-width="0"
                :disabled="!isEditing"
                class="contact-form"
              >
                <el-form-item prop="mail">
                  <label class="form-label">邮箱地址</label>
                  <el-input 
                    v-model="formData.mail" 
                    placeholder="请输入邮箱地址"
                    :prefix-icon="Message"
                  />
                </el-form-item>
                <el-form-item prop="phone">
                  <label class="form-label">手机号码</label>
                  <el-input 
                    v-model="formData.phone" 
                    placeholder="请输入手机号码"
                    :prefix-icon="Phone"
                  />
                </el-form-item>
                <el-form-item prop="contact">
                  <label class="form-label">紧急联系人</label>
                  <el-input 
                    v-model="formData.contact" 
                    placeholder="请输入紧急联系人"
                    :prefix-icon="UserFilled"
                  />
                </el-form-item>
              </el-form>
            </div>
          </el-col>

          <!-- 右侧：账户信息 -->
          <el-col :span="12">
            <div class="info-section">
              <div class="section-title">
                <el-icon><Lock /></el-icon>
                <span>账户信息</span>
              </div>
              <el-form 
                :model="formData" 
                :rules="rules" 
                ref="formRef" 
                label-width="0"
                :disabled="!isEditing"
                class="account-form"
              >
                <el-form-item prop="username">
                  <label class="form-label">用户名</label>
                  <el-input 
                    v-model="formData.username" 
                    placeholder="请输入用户名"
                    :prefix-icon="User"
                  />
                </el-form-item>
                <el-form-item prop="password">
                  <label class="form-label">密码</label>
                  <el-input 
                    v-model="formData.password" 
                    type="password" 
                    show-password
                    placeholder="请输入密码"
                    :prefix-icon="Lock"
                  />
                </el-form-item>
              </el-form>
            </div>

            <!-- 操作按钮 -->
            <div v-if="isEditing" class="action-buttons">
              <el-button type="primary" @click="saveProfile" :loading="saving" size="large">
                <el-icon><Check /></el-icon>
                保存修改
              </el-button>
              <el-button @click="cancelEdit" size="large">
                <el-icon><Close /></el-icon>
                取消
              </el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { User, Lock, Phone, Message, UserFilled, Check, Close } from '@element-plus/icons-vue';
import axios from 'axios';

const student = ref(null);
const loading = ref(false);
const saving = ref(false);
const error = ref(null);
const isEditing = ref(false);
const formRef = ref(null);
const contactFormRef = ref(null);

const formData = reactive({
  username: '',
  password: '',
  mail: '',
  phone: '',
  contact: '',
  name: '',
  college: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '用户名长度不能少于2位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  mail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入紧急联系人', trigger: 'blur' }
  ]
};

const loadProfile = async () => {
  loading.value = true;
  error.value = null;
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      error.value = '请先登录';
      return;
    }

    const response = await axios.get('/api/student/profile', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });

    if (response.data.code === 0) {
      const s = response.data.data;
      student.value = s;
      
      // 更新表单数据（只更新可编辑的字段）
      Object.assign(formData, {
        username: s.username,
        password: s.password,
        mail: s.mail,
        phone: s.phone,
        contact: s.contact,
        name: s.name,
        college: s.college
      });
    } else {
      error.value = response.data.msg || '加载失败';
    }
  } catch (err) {
    error.value = '请求失败: ' + err.message;
    console.error('错误详情:', err);
  } finally {
    loading.value = false;
  }
};

const toggleEdit = () => {
  if (isEditing.value) {
    cancelEdit();
  } else {
    isEditing.value = true;
  }
};

const cancelEdit = () => {
  isEditing.value = false;
  // 重置表单数据为原始数据
  if (student.value) {
    Object.assign(formData, {
      username: student.value.username,
      password: student.value.password,
      mail: student.value.mail,
      phone: student.value.phone,
      contact: student.value.contact,
      name: student.value.name,
      college: student.value.college
    });
  }
  formRef.value?.clearValidate();
  contactFormRef.value?.clearValidate();
};

const saveProfile = async () => {
  if (!formRef.value || !contactFormRef.value) return;
  
  try {
    await Promise.all([
      formRef.value.validate(),
      contactFormRef.value.validate()
    ]);
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确');
    return;
  }

  saving.value = true;
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('请先登录');
      return;
    }

    const updateData = {
      username: formData.username,
      password: formData.password,
      mail: formData.mail,
      phone: formData.phone,
      name: formData.name,
      college: formData.college,
      contact: formData.contact
    };

    const response = await axios.put('/api/student/profile', updateData, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });

    if (response.data.code === 0) {
      ElMessage.success('个人信息更新成功');
      isEditing.value = false;
      // 重新加载数据
      await loadProfile();
    } else {
      ElMessage.error(response.data.msg || '更新失败');
    }
  } catch (err) {
    ElMessage.error('更新失败: ' + err.message);
    console.error('更新错误详情:', err);
  } finally {
    saving.value = false;
  }
};

onMounted(() => {
  loadProfile();
});
</script>

<style scoped>
.profile-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.profile-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  border: 3px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.user-role {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.header-right {
  display: flex;
  gap: 12px;
}

.loading-container {
  padding: 40px 20px;
}

.error-container {
  padding: 40px 20px;
}

.profile-content {
  padding: 24px;
}

.info-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
}

.section-title .el-icon {
  font-size: 18px;
  color: #409eff;
}

.info-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 12px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.info-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.1);
}

.info-label {
  font-size: 13px;
  color: #909399;
  font-weight: 500;
}

.info-value {
  font-size: 15px;
  color: #303133;
  font-weight: 500;
}

.account-form,
.contact-form {
  margin-top: 12px;
}

.form-label {
  display: block;
  margin-bottom: 6px;
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.el-form-item {
  margin-bottom: 16px;
}

.el-input {
  border-radius: 6px;
}

.el-input__wrapper {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.el-input__wrapper:hover {
  border-color: #409eff;
}

.el-input__wrapper.is-focus {
  border-color: #409eff;
  box-shadow: 0 0 0 1px #409eff;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.el-button {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.el-button--primary {
  background: #409eff;
  border: none;
}

.el-button--primary:hover {
  background: #36a3f7;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 16px;
  }
  
  .profile-content {
    padding: 16px;
  }
  
  .header-left {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
  
  .user-name {
    font-size: 18px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .el-col {
    margin-bottom: 16px;
  }
}
</style>
